//
//  ListViewController.m
//  iMiniTao
//
//  Created by liu nian on 13-8-17.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "ListViewController.h"
#import "DataManager.h"
#import "MeSource.h"
#import "ItemCell.h"
#import "RefreshCell.h"
#import "LolayGridView.h"
#import "ItemViewController.h"
#import "SDWebImagePrefetcher.h"

#define kLandscapeNum    5
;

@interface ListViewController ()<DataManagerDelegate,LolayGridViewDataSource,LolayGridViewDelegate,RefreshCellDelegate>{
    NSInteger   _index;
    BOOL        _reload;
    BOOL        _loadMore;
    CGPoint     _contentOffset;
}
@property (nonatomic, strong) LolayGridView *gridView;
@property (nonatomic, strong) RefreshCell *headerCell;
@property (nonatomic, strong) RefreshCell   *footerCell;
@property (nonatomic, strong) NSMutableArray    *datasource;
@property (nonatomic, strong) UIImageView          *bottomImageView;
@property (nonatomic, strong) UILabel       *theTitle;
@property (nonatomic, strong) MeSource  *source;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@end

@implementation ListViewController

- (void)dealloc{
    BMLog(@"cancelAll");
    [[DataManager sharedInstance] setDelegate:nil];
    [[SDWebImagePrefetcher sharedImagePrefetcher] cancelPrefetching];
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDWebImageManager sharedManager] cancelAll];
    [self.datasource removeAllObjects];
    self.datasource = nil;

    _headerCell.delegate = nil;
    _footerCell.delegate = nil;
    _gridView.dataSource = nil;
    _gridView.dataDelegate = nil;
    self.gridView = nil;
    self.headerCell=nil;
    self.footerCell = nil;
    self.bottomImageView = nil;
    self.theTitle = nil;
    self.source = nil;
    self.indicatorView = nil;
}

- (id)initWithMeSource:(MeSource *)source
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.source = source;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [self orientationChanged:[UIApplication sharedApplication].statusBarOrientation];
}

#pragma mark -
#pragma mark  handle orientation change
- (void)orientationChanged:(UIInterfaceOrientation)currentOrientation
{
//    [_navImageView setFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 58)];
//    _gridView.frame = CGRectMake(0,
//                                 CGRectGetMaxY(self.navImageView.frame),
//                                 CGRectGetWidth(self.view.bounds),
//                                 CGRectGetHeight(self.view.bounds) - CGRectGetMaxY(self.navImageView.frame));
//    [_gridView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[DataManager sharedInstance] setDelegate:nil];
    [[SDWebImagePrefetcher sharedImagePrefetcher] cancelPrefetching];
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDWebImageManager sharedManager] cancelAll];
    [self.datasource removeAllObjects];
    self.datasource = nil;
    _gridView.dataSource = nil;
    _gridView.dataDelegate = nil;
    self.gridView = nil;
    _headerCell.delegate = nil;
    _footerCell.delegate = nil;
    self.headerCell=nil;
    self.footerCell = nil;
    self.bottomImageView = nil;
    self.theTitle = nil;
    self.source = nil;

    self.indicatorView = nil;
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)tableViewDidScrollToTop{
    [self.gridView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self bottomImageView];
    self.theTitle.text = self.source.name;
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          self.source.themeid, @"themeid",self.source.name, @"name", nil];
    [MobClick event:@"showProductList" attributes:dict];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    if (self.datasource.count == 0) {
        [self reloadItems];
    }
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[SDWebImagePrefetcher sharedImagePrefetcher] cancelPrefetching];
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDWebImageManager sharedManager] cancelAll];
//    [self.datasource removeAllObjects];
//    self.datasource = nil;
//    [_flowView unloadData];
//    _flowView.delegate = nil;
//    _flowView.flowDelegate = nil;
//    self.flowView = nil;


}

- (void)loadData{
    if (self.source.custom || self.source.itemtype == ITEMTYPEKEYWORD) {
        [[DataManager sharedInstance] requstTBKItemsWithKeyWord:self.source.name
                                                    WithThemeID:nil
                                                WithPicSizeType:PicSize360
                                                       WithSort:nil
                                                  WithPageIndex:0 withDelegate:self];
    }else{
        [[DataManager sharedInstance] requstTBKItemsWithKeyWord:nil
                                                    WithThemeID:self.source.themeid
                                                WithPicSizeType:PicSize360
                                                       WithSort:nil
                                                  WithPageIndex:0
                                                   withDelegate:self];
    }
}
- (void)reloadItems{
    if (_reload) {
        return;
    }
    [self.indicatorView startAnimating];
    _reload = YES;
    _index =0;
    [self loadData];
}
- (void)reloadMoreItems{

    if (_loadMore) {
        return;
    }
//    _contentOffset = self.flowView.contentOffset;
    [self.indicatorView startAnimating];
    _loadMore = YES;
    _index++;
    [self loadData];
    
}
#pragma mark  DataManagerDelegate
-(void) updateViewForSuccess:(id)dataModel{
    [self.indicatorView stopAnimating];
    NSMutableArray *items = dataModel;
    if (self.datasource.count == 0) {
        [self footerCell];
    }
    
    if (items && [items count]) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (_reload) {
                _reload = NO;
                _index = 0;
                if ([items count] > 0) {
                    [self.datasource removeAllObjects];
                    [self.datasource addObjectsFromArray:items];
                }
            }
            
            if (_loadMore) {
                _loadMore = NO;
                [self.datasource addObjectsFromArray:items];
            }
            
            [self.gridView reloadData];
            //                [self.flowView setContentOffset:_contentOffset animated:NO];
            if (!self.source.custom) {
                [self.headerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
            }
            [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
        });
        
        return;
        NSMutableArray  *imageURLs = [[NSMutableArray alloc] initWithCapacity:items.count];
        NSMutableArray *cItems = [[NSMutableArray alloc] initWithCapacity:items.count];
        [items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            CuzyTBKItem *item = obj;
//            
//            IIIBaseData *data = [[IIIBaseData alloc] init];
//            data.local_url = [[SDImageCache sharedImageCache] defaultCachePathForKey:item.itemImageURLString];
//            data.web_url = item.itemImageURLString;
//            data.item = item;
//            [cItems addObject:data];
            [imageURLs addObject:item.itemImageURLString];
        }];
        
        [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:imageURLs completed:^(NSUInteger finishedCount, NSUInteger skippedCount) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (_reload) {
                    _reload = NO;
                    _index = 0;
                    if ([items count] > 0) {
                        [self.datasource removeAllObjects];
                        [self.datasource addObjectsFromArray:cItems];
                    }
                }
                
                if (_loadMore) {
                    _loadMore = NO;
                    [self.datasource addObjectsFromArray:cItems];
                }
                
                [self.gridView reloadData];
//                [self.flowView setContentOffset:_contentOffset animated:NO];
                if (!self.source.custom) {
                    [self.headerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
                }
                [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
            });
        }];
        

        
    }else{
        [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
        REMOVE_SAFELY(_footerCell);
    }
}
-(void) updateViewForError:(NSError *)errorInfo{
    [self.indicatorView stopAnimating];
    if (!self.source.custom) {
        [self.headerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
    }
    [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
    
    if (_reload) {
        _reload = NO;
    }
    
    if (_loadMore) {
        _loadMore = NO;
        _index--;
    }
}

#pragma mark LolayGridViewDataSource
- (NSInteger)numberOfRowsInGridView:(LolayGridView*)gridView
{
    NSInteger count = [self.datasource count];
    return ceil(1.0f*count/kLandscapeNum);
}
- (NSInteger)numberOfColumnsInGridView:(LolayGridView*)gridView
{
    return kLandscapeNum;
}

- (LolayGridViewCell*)gridView:(LolayGridView*)gridView
                    cellForRow:(NSInteger)gridRowIndex
                      atColumn:(NSInteger)gridColumnIndex
{
    CGFloat width = CGRectGetWidth(self.view.bounds) /kLandscapeNum;
    NSInteger objectIndex = gridRowIndex * kLandscapeNum + gridColumnIndex;
    if (objectIndex >= [self.datasource count]) {
        return nil;
    }
    
    static NSString *cellID = @"newsCell";
    ItemCell *cell = (ItemCell *)[gridView dequeueReusableGridCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[ItemCell alloc] initWithFrame:CGRectMake(0, 0, width, width + kDefaultCellBottomBarHeight) reuseIdentifier:cellID];
    }
    CuzyTBKItem *item = (CuzyTBKItem *)[self.datasource objectAtIndex:objectIndex];
    [cell updateWithItem:item];
    return cell;
}

#pragma mark LolayGridViewDelegate
- (CGFloat)heightForGridViewRows:(LolayGridView*)gridView
{
    return CGRectGetWidth(self.view.bounds) /kLandscapeNum + kDefaultCellBottomBarHeight;
}
- (CGFloat)widthForGridViewColumns:(LolayGridView*)gridView
{
    return CGRectGetWidth(self.view.bounds) /kLandscapeNum;;
}
- (void)gridView:(LolayGridView*)gridView
didSelectCellAtRow:(NSInteger)gridRowIndex
        atColumn:(NSInteger)gridColumnIndex
{
    
    NSInteger objectIndex = gridRowIndex * kLandscapeNum + gridColumnIndex;
    
    ItemCell *cell = (ItemCell *)[gridView cellForRow:gridRowIndex atColumn:gridColumnIndex];
    
    CuzyTBKItem *item = (CuzyTBKItem *)[self.datasource objectAtIndex:objectIndex];
    ItemViewController *itemVC = [[ItemViewController alloc] initWithMeItem:item];
    itemVC.shareImage = cell.srcImageView.image;
    [self.navigationController pushViewController:itemVC animated:YES];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (!self.source.custom) {
        [self.headerCell refreshScrollViewDidScroll:scrollView];
    }
    [_footerCell refreshScrollViewDidScroll:scrollView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (!self.source.custom) {
        [self.headerCell refreshScrollViewDidEndDragging:scrollView];
    }
    [_footerCell refreshScrollViewDidEndDragging:scrollView];
}

#pragma mark - RefreshCellDelegate
- (void)refreshCellDidTriggerLoading:(RefreshCell*)view{
    if (self.source.custom){
        if (view == _footerCell) {
            [self reloadMoreItems];
        }
    }else{
        if (view == self.headerCell) {
            [self reloadItems];
        }else
            if (view == _footerCell) {
                [self reloadMoreItems];
            }
    }


}

- (BOOL)refreshCellDataSourceIsLoading:(RefreshCell*)view{
    if (self.source.custom) {
        return  _footerCell.state==RefreshLoading;
    }else{
        return self.headerCell.state == RefreshLoading || _footerCell.state==RefreshLoading;
    }
}

- (NSDate*)refreshCellDataSourceLastUpdated:(RefreshCell*)view{
    return [NSDate date];
}
#pragma mark - getter
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,
                                                                         CGRectGetHeight(self.view.bounds) - kDefaultBottomBarHeight -_kSpaceHeight,
                                                                         CGRectGetWidth(self.view.bounds),
                                                                         kDefaultBottomBarHeight)];
        _bottomImageView.backgroundColor = COLOR_RGB_BOTTOM;
        _bottomImageView.userInteractionEnabled = YES;
        
        UIImage *image = [IMGNAMED(@"bg_navback.png") resizableImageWithCapInsets:UIEdgeInsetsMake(2, 2, 2, 2)];
        [_bottomImageView setImage:image];
        
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        
        [back setBackgroundImage:IMGNAMED(@"btn_back.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_back_light.png") forState:UIControlStateHighlighted];
        [self.view addSubview:_bottomImageView];
    }
    return _bottomImageView;
}

- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
    }
    return _indicatorView;
}
- (UILabel *)theTitle{
    if (!_theTitle) {
        _theTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 4, 260, 50)];
        _theTitle.backgroundColor = [UIColor clearColor];
        _theTitle.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
        _theTitle.font = FONT_TITLE(18.0f);
        _theTitle.textColor = [UIColor flatDarkBlackColor];
        _theTitle.text = @"频道订阅";
        [self.bottomImageView addSubview:_theTitle];
    }
    return _theTitle;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        _datasource = [[NSMutableArray alloc] initWithCapacity:20];
    }
    return _datasource;
}

- (LolayGridView *)gridView{
    if (!_gridView) {
        _gridView = [[LolayGridView alloc] initWithFrame:CGRectMake(0,
                                                                 0,
                                                                 CGRectGetWidth(self.view.bounds),
                                                                 CGRectGetHeight(self.view.bounds) - 58 -_kSpaceHeight)];
        _gridView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _gridView.backgroundColor = [UIColor colorWithRed:160/225.0 green:160/225.0 blue:130/225.0 alpha:1.0];
        _gridView.backgroundColor = [UIColor colorWithPatternImage:IMGNAMED(@"wall_filter_bg_body.png")];
        _gridView.topBounceEnabled = YES;
        _gridView.dataDelegate = self;
        _gridView.dataSource = self;
        _gridView.delegate = self;
        _gridView.showsVerticalScrollIndicator = NO;
        _gridView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_gridView];
    }
    return _gridView;
}

- (RefreshCell *)headerCell {
    if (!_headerCell) {
        _headerCell = [RefreshCell attachRefreshCellTo:self.gridView
                                               delegate:self
                                         arrowImageName:@"refreshcell_img_arrow.png"
                                              textColor:[UIColor flatGrayColor]
                                         indicatorStyle:UIActivityIndicatorViewStyleGray
                                                   type:RefreshTypeRefresh];
    }
    return _headerCell;
}
- (RefreshCell *)footerCell {
    if (!_footerCell) {
        _footerCell = [RefreshCell attachRefreshCellTo:self.gridView
                                               delegate:self
                                         arrowImageName:@"refreshcell_img_arrow.png"
                                              textColor:[UIColor flatGrayColor]
                                         indicatorStyle:UIActivityIndicatorViewStyleGray
                                                   type:RefreshTypeLoadMore];
    }
    return _footerCell;
}

@end
